<template>
  <vxe-modal :title="title" v-model="visible" @close="close()" width="900px" :position="{ top: 100 }">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" inline :disabled="type == 'detail'">
      <el-form-item label="项目名称" prop="projectName">
        <el-input placeholder="请输入" clearable v-model="form.projectName"></el-input>
      </el-form-item>
      <el-form-item label="项目简称" prop="nickName">
        <el-input placeholder="请输入" clearable v-model="form.nickName"></el-input>
      </el-form-item>
      <el-form-item label="所属组织">
        <el-tree-select
          check-strictly
          clearable
          v-model="form.orgId"
          :props="{ label: 'orgName', value: 'id', children: 'childList' }"
          :data="options.organization"
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item label="发薪模式">
        <el-select v-model="form.payType" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in options.projectPayType"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="+item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目周期">
        <el-select v-model="form.projectPeriod" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in options.projectPeriod"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="+item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目开始日期">
        <el-date-picker v-model="form.beginData" type="date" clearable placeholder="请选择" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="项目结束日期">
        <el-date-picker v-model="form.endData" type="date" clearable placeholder="请选择" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="项目负责人">
        <el-input placeholder="请输入" clearable v-model="form.projectLeader"></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input placeholder="请输入" clearable v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="经营模式">
        <el-select v-model="form.businessModel" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in options.businessModel"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="+item.dictValue"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同签署">
        <el-select v-model="form.contractSign" placeholder="请选择" clearable>
          <el-option label="是" :value="true"></el-option>
          <el-option label="否" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="合同模板" prop="contractModelId" v-if="form.contractSign">
        <el-select v-model="form.contractModelId" placeholder="请选择" clearable filterable>
          <el-option
            v-for="item in options.contractModelList"
            :key="item.id"
            :label="item.contractModelName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="小程序打卡" prop="smallProgramClock">
        <el-select v-model="form.smallProgramClock" placeholder="请选择" clearable filterable>
          <el-option label="是" :value="true"></el-option>
          <el-option label="否" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="打卡范围" prop="clockDistance" v-if="form.smallProgramClock">
        <el-input v-number placeholder="请输入" clearable v-model="form.clockDistance"></el-input>
      </el-form-item>
    </el-form>

    <div class="line"></div>

    <vxe-grid
      ref="supplierGrid"
      v-bind="supplierGridConfig"
      class="sticky-header"
      v-if="form.businessModel && form.businessModel != '1'"
    >
      <template #toolbar_buttons>
        <el-button icon="PlusIcon" @click="addSupplier({ level: 0 })" v-if="type != 'detail'">增加一级供应商</el-button>
      </template>
      <template #supplierId="{ row, level }">
        <el-select v-model="row.supplierId" placeholder="请选择" clearable filterable :disabled="type == 'detail'">
          <el-option 
            v-for="item in getCurrSupplier(level)"
            :key="item.id" 
            :label="item.supplierName" 
            :value="item.id"
          >
          </el-option>
        </el-select>
      </template>
      <template #operate="{ row, level }">
        <el-button 
          link 
          @click="addSupplier({ row, level: 1 })" 
          v-if="level == 0 && form.businessModel == '3' && type != 'detail'"
        >增加二级供应商</el-button>
        <el-button link type="danger" @click="deleteSupplier({ row, level })" v-if="type != 'detail'">删除</el-button>
      </template>
    </vxe-grid>
    <template #footer>
      <div v-if="type != 'detail'">
        <el-button @click="close()">关闭</el-button>
        <el-button type="primary" @click="submit()">确定</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script lang="ts" setup>
import { VxeGridInstance } from "vxe-table"
import { ref, defineExpose, reactive, defineProps, defineEmits } from "vue"
import { commonRules } from "@/utils/validate"
import { VxeGridProps } from "vxe-table"
import { projectAdd, projectEdit, projectGetInfo } from "@/api/projectManage/project"
import { contractModelDropdownList } from "@/api/public"
import { ElMessage } from "element-plus"

import { Type, Id, Form } from "./type"

let type = ref<Type>("add")
let id = ref<Id>("")
const title = ref("")
const visible = ref(false)
const emits = defineEmits(["refreshList"])
const props = defineProps<{
  options: any
}>()

// 表单逻辑
const formRef = ref()
const form = reactive(setDefaultForm())
const rules = reactive({
  projectName: commonRules.requiredInput,
  nickName: commonRules.requiredInput,
  contractModelId: commonRules.requiredSelect,
  clockDistance: commonRules.requiredInput
})

function setDefaultForm(): Form {
  return {
    businessModel: "",
    beginData: "",
    clockDistance: "",
    contractModelId: "",
    contractSign: false,
    endData: "",
    nickName: "",
    orgId: "",
    payType: "",
    phone: "",
    projectLeader: "",
    projectName: "",
    projectPeriod: "",
    smallProgramClock: false,
    supplierList: []
  }
}

function submit() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return

    const api = type.value == "add" ? projectAdd : projectEdit

    api(form).then(() => {
      ElMessage.success("操作成功")
      close()
      emits("refreshList")
    })
  })
}

function close() {
  visible.value = false
  Object.assign(form, setDefaultForm())
  formRef.value.resetFields()
}

function open({ type: t, id: i }: { type: Type; id?: Id }) {
  type.value = t
  id.value = i
  title.value = { add: "新增项目", edit: "编辑项目", detail: "项目详情" }[type.value]

  getInfo()
  getContractModelDropdownList()
  visible.value = true
}

function getInfo() {
  if (type.value === "add") return

  projectGetInfo({ id: id.value }).then((res) => {
    Object.assign(form, res.data)

    if (!form.supplierList.length) return;

    setTimeout(() => {
      supplierGrid.value.reloadData(form.supplierList)
    }, 100)
  })
}

// 获取合同下拉列表
function getContractModelDropdownList() {
  contractModelDropdownList().then((res) => {
    props.options.contractModelList = res.data
  })
}

// 供应商逻辑
const supplierGrid: any = ref<VxeGridInstance>()
const supplierGridConfig: any = reactive<VxeGridProps>({
  stripe: false,
  toolbarConfig: {
    custom: true,
    slots: {
      buttons: "toolbar_buttons"
    }
  },
  expandConfig: {
    reserve: true
  },
  treeConfig: {
    rowField: "_X_ROW_KEY",
    children: "childSupplierList"
  },
  columns: [
    { type: "seq", width: 50 },
    { title: "供应商", field: "supplierId", width: 180, treeNode: true, slots: { default: "supplierId" } },
    { title: "联系人", field: "contactName" },
    { title: "联系方式", field: "contactPhone" },
    { title: "操作", field: "operate", slots: { default: "operate" }, showOverflow: false, width: 180 }
  ],
  data: []
})

async function addSupplier({ row, level }: { row?: any; level: number }) {
  if (level === 0) {
    form.supplierList.push({
      supplierId: "",
      contactName: "",
      childSupplierList: []
    })
    supplierGrid.value.reloadData(form.supplierList)
  } else if (level === 1) {
    row.childSupplierList.push({
      supplierId: "",
      contactName: ""
    })
    supplierGrid.value.reloadData(form.supplierList)
    supplierGrid.value.setTreeExpand(row, true) // 将父节点展开
  }
}

function deleteSupplier({ row, level }: { row: any; level: number }) {
  if (level === 0) {
    form.supplierList = form.supplierList.filter((item: any) => item._X_ROW_KEY !== row._X_ROW_KEY)
    supplierGrid.value.reloadData(form.supplierList)
  } else if (level === 1) {
    const parentRow = supplierGrid.value.getParentRow(row)
    parentRow.childSupplierList = parentRow.childSupplierList.filter((item: any) => item._X_ROW_KEY !== row._X_ROW_KEY)
    supplierGrid.value.reloadData(form.supplierList)
    supplierGrid.value.setTreeExpand(parentRow, true)
  }
}

function getCurrSupplier(level: number): any[] {
  if (level == 0) {
    return props.options.oneLevelSupplierList
  } else if (level == 1) {
    return props.options.twoLevelSupplierList
  } else {
    return []
  }
}

defineExpose({ close, open })
</script>

<style lang="scss" scoped>
@import "@/styles/mixins.scss";

.el-form {
  @include grid-container($columns: 4);
}
</style>
